﻿using System;
using System.Data.SqlClient;
using System.Reflection;
using NHibernate.Cfg;

namespace BitworkStudios.Data.NhEzPlugin
{
    public abstract class NHibernateSessionBase : IDisposable, IRepository
    {
        private readonly Configuration _config;
        private readonly NHibernate.ISessionFactory _factory;
        public readonly NHibernate.ISession Session;
        private readonly NHibernate.ITransaction _transaction;
        private readonly SqlConnection _activeConnection;

        public abstract string ConnectionString { get; }

        protected NHibernateSessionBase()
        {
            _config = new Configuration().Configure();
            _config.AddAssembly(Assembly.GetCallingAssembly());

            _factory = _config.BuildSessionFactory();

            _activeConnection = new SqlConnection(ConnectionString);
            _activeConnection.Open();
            Session = _factory.OpenSession(_activeConnection);
            _transaction = Session.BeginTransaction();
        }

        public void Dispose()
        {
            _transaction.Commit();
            Session.Close();
            _activeConnection.Close();
        }
    }
}
